package edu.ynu.hhy.architectureclass.controller;

import edu.ynu.hhy.architectureclass.entity.*;
import edu.ynu.hhy.architectureclass.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class GreenhouseController {

    @Autowired
    private SensorDataService sensorDataService;

    @Autowired
    private GreenhouseService greenhouseService;

    @Autowired
    private CameraDataService cameraDataService;

    // 1. 根据device的name获取对应sensor的数据
    @GetMapping("/sensor-data")
    public Double getSensorDataByName(@RequestParam String name) {
        List<SensorData> sensorDataList = sensorDataService.getSensorData();
        for (SensorData sensorData : sensorDataList) {
            if (sensorData.getName().equals(name)) {
                return sensorData.getValue();
            }
        }
        return null;
    }

    // 2. 获取greenhouse的信息（名字、地址、面积）
    @GetMapping("/greenhouse/{id}")
    public Greenhouse getGreenhouseInfo(@PathVariable Long id) {
        return greenhouseService.getGreenhouseDetailWithDeviceCount(id);
    }

    // 3. 获取土壤氮含量最近五天的value值变化
    @GetMapping("/soil-nitrogen")
    public List<Double> getSoilNitrogenData(
            @RequestParam String date, // 前端传递的日期
            @RequestParam String sensorName // 前端传递的传感器名称
    ) {
        // 验证传感器名称是否为 "土壤氮含量"
        if (!"土壤氮含量".equals(sensorName)) {
            throw new IllegalArgumentException("传感器名称不正确");
        }

        // 假设土壤氮含量的传感器名称为 "土壤氮含量传感器"
        List<SensorData> sensorDataList = sensorDataService.getSensorData();
        List<Double> nitrogenValues = new ArrayList<>();
        for (SensorData sensorData : sensorDataList) {
            if ("土壤氮含量传感器".equals(sensorData.getName())) {
                nitrogenValues.add(sensorData.getValue());
            }
        }

        // 返回最近五天的土壤氮含量数据
        return nitrogenValues;
    }

    // 4. 获取cameradata表里的picURL，将图片展示到前端
    @GetMapping("/camera-image")
    public String getCameraImageUrl(@RequestParam String deviceSerial) {
        CameraData cameraData = cameraDataService.captureAndSaveCameraImage(deviceSerial, "your-access-token");
        return cameraData != null ? cameraData.getPicUrl() : null;
    }
}